<?php
namespace app\common\controller;
use app\BaseController;
use app\common\model\Nav;
use think\exception\HttpResponseException;
use think\facade\View;
use think\facade\Request;

class HomeBase extends BaseController
{
    use \app\common\traits\JumpTrait;
    protected $webRoot;
    protected $model;
    protected $params;
    //静态模板生成目录
    protected $staticHtmlDir = "";
    //静态文件
    protected $staticHtmlFile = "";
    protected function initialize()
    {
        $this->params = request()->param();
        $this->assign('nav1',Nav::getItems(1));
        $this->assign('nav2',Nav::getItems(2));

        $this->assign('hotTags', getJsonData('Tag','hot',[],28));
        //action
        $controller = Request::instance()->controller();
        $action = Request::instance()->action();

        $this->assign('controller', $controller);
        $this->assign('action', $action);
        $this->assign('URI', null);
        $site=sysconfig('site');
        $this->assign('site', ['name'=>$site['site_name'],'title'=>$site['short_desc'],'description'=>$site['description'],'keywords'=>$site['keywords']]);

    }

    protected function loginError(){
        $this->redirect(__url('user/login/index'));
    }

    protected function assign(...$vars)
    {
        View::assign(...$vars);
    }

    protected function fetch(string $template = '')
    {
        return View::fetch($template);
    }

    protected function redirect(...$args){
        throw new HttpResponseException(redirect(...$args));
    }


    //判断是否存在静态
    public function beforeBuild($param = []) {
        //生成静态
        $this->staticHtmlDir = "html".DS.$this->request->controller().DS;
        //参数md5
        $param = md5(json_encode($param));
        $this->staticHtmlFile = $this->staticHtmlDir .$this->request->action() . '_'  . $param .'.html';

        //目录不存在，则创建
        if(!file_exists($this->staticHtmlDir)){
            mkdir($this->staticHtmlDir);
        }
        //静态文件存在,并且没有过期
        if(file_exists($this->staticHtmlFile) && filectime($this->staticHtmlFile)>=time()-60*4) {
            header("Location:/" . $this->staticHtmlFile);
            exit();
        }
    }

    //开始生成静态文件
    public function afterBuild($html) {
        if(!empty($this->staticHtmlFile) && !empty($html)) {
            if(file_exists($this->staticHtmlFile)) {
                \unlink($this->staticHtmlFile);
            }
            if(file_put_contents($this->staticHtmlFile,$html)) {
                header("Location:/" . $this->staticHtmlFile);
                exit();
            }
        }
    }
}